package com.denlaku.longan.controller.impl;

import com.denlaku.longan.controller.ImageResourceController;
import com.denlaku.longan.qo.Query;
import com.denlaku.longan.service.ResourceService;
import com.denlaku.longan.vo.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * @author tianx
 */
@RestController
@Slf4j
public class ImageResourceControllerImpl implements ImageResourceController {
    @Autowired
    private ResourceService resourceService;

    @Override
    public void image(@PathVariable("tenantId") Long tenantId, @PathVariable("id") Long id,
            HttpServletResponse response) {
        Resource resource = resourceService.get(Query.of(tenantId, id));
        if (resource == null) {
            response.setStatus(404);
            return;
        }
        File file = resourceService.toFile(resource);
        if (!file.exists()) {
            response.setStatus(404);
            return;
        }
        try {
            response.setContentType(resource.getContentType());
            response.setContentLengthLong(file.length());
            Files.copy(file.toPath(), response.getOutputStream());
        } catch (IOException e) {
            log.error("get image error", e);
        }
    }

}
